package com.fourforfo.fourmall.order.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayConfig;
import com.alipay.api.internal.util.AlipaySignature;
import com.fourforfo.fourmall.order.config.AlipayTemplate;
import com.fourforfo.fourmall.order.service.OrderService;
import com.fourforfo.fourmall.order.vo.alipay.PayAsyncVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.misc.Request;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @program: xxl-sso-core
 * @description: 订单支付异步通知监听器
 * @author: fourforfo
 * @email: fourforfo@gmail.com
 * @create: 2022-09-13 12:05
 **/
@Slf4j
@RestController
public class OrderPayedNotifyListener {

    @Autowired
    OrderService orderService;

    @Autowired
    AlipayTemplate alipayTemplate;

    @PostMapping("/payed/notify")
    public String handleAlipayedNotify(PayAsyncVO payAsyncVO, HttpServletRequest request) throws UnsupportedEncodingException, AlipayApiException {

//        log.info("接受到异步通知请求，请求参数为："+payAsyncVO);


        //验签
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params,alipayTemplate.getAlipay_public_key() , alipayTemplate.getCharset(), alipayTemplate.getSign_type()); //调用SDK验证签名

        //验证不通过，返回错误信息
        if(!signVerified){
            log.info("异步通知验证失败");
            return "fail";
        }
        /**
         * 处理支付宝异步通知
         */
        log.info("异步通知验证成功");
        String result = orderService.handlePayResult(payAsyncVO);

        //处理完异步通知后必须也只能返回success，返回其他的话支付宝还是会不断发送请求通知我们
        return result;
    }
}
